package cn.b.sky.mes.mm.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.b.sky.mes.cm.model.WorkCenter;
import cn.b.sky.mes.cm.model.WorkUnit;
import cn.b.sky.mes.cm.service.WorkCenterService;
import cn.b.sky.mes.cm.service.WorkUnitService;
import cn.b.sky.mes.mm.model.MessageConfig;
import cn.b.sky.mes.mm.model.condition.MessageConfigCondition;
import cn.b.sky.mes.mm.service.MessageConfigService;
import cn.b.sky.common.constants.SystemConstant;
import cn.b.sky.common.model.BatchJobReport;
import cn.b.sky.common.model.DWZResult;
import cn.b.sky.user.controller.SecurityController;

/**
 * 
 * <strong>Title : MessageConfigController.java<br></strong>
 * <strong>Package : cn.b.sky.mes.mm.controller<br></strong>
 * <strong>Description : </strong>物料拉动消息配置控制器<br> 
 * <strong>Create on : 2016年9月10日 上午9:24:18<br></strong>
 * <p>
 * @author dapeng.li<br>
 * @version <strong>v1.0.0</strong><br>
 * <br>
 * <strong>修改历史:</strong><br>
 * 修改人|修改日期|修改描述<br>
 * -------------------------------------------<br>
 * <br>
 * <br>
 */
@Controller
@RequestMapping("/msgConfig/*")
public class MessageConfigController extends SecurityController {

  private static final String CONFIG_PAGE = "mm/msgConfig/configPage";

  @Autowired
  private WorkCenterService workCenterService;

  @Autowired
  private WorkUnitService workUnitService;

  @Autowired
  private MessageConfigService messageConfigService;

  @RequestMapping("listPage")
  public String listPage(Model model, String navTabId) {
    model.addAttribute(NAVTABID, navTabId);
    // 组装工作中心
    List<WorkCenter> workCenters = workCenterService.getAllWorkCenterListBySiteCode(getSiteCode(), 0);
    Map<String, List<WorkCenter>> centerMap = new HashMap<String, List<WorkCenter>>();
    centerMap.put("", new LinkedList<WorkCenter>());
    for (WorkCenter workCenter : workCenters) {
      if (StringUtils.isEmpty(workCenter.getParentWorkCenterCode())) {
        centerMap.get("").add(workCenter);
      } else {
        if (!centerMap.containsKey(workCenter.getParentWorkCenterCode())) {
          centerMap.put(workCenter.getParentWorkCenterCode(), new LinkedList<WorkCenter>());
        }
        centerMap.get(workCenter.getParentWorkCenterCode()).add(workCenter);
      }
    }
    // 组装作业单元
    List<WorkUnit> workUnits = workUnitService.getAllWorkUnitListBySiteCode(getSiteCode(), 0);
    Map<String, List<WorkUnit>> centerUnitMap = new HashMap<String, List<WorkUnit>>();
    for (WorkUnit workUnit : workUnits) {
      if (!centerUnitMap.containsKey(workUnit.getWorkCenterCode())) {
        centerUnitMap.put(workUnit.getWorkCenterCode(), new LinkedList<WorkUnit>());
      }
      centerUnitMap.get(workUnit.getWorkCenterCode()).add(workUnit);
    }
    List<WorkCenter> workCentersTree = centerMap.get("");
    setChildren(centerMap, centerUnitMap, workCentersTree);
    model.addAttribute("workCentersTree", workCentersTree);
    return "mm/msgConfig/listPage";
  }

  /**
   * 
   * <strong>Title : setChildren<br></strong>
   * <strong>Description : </strong>设置工作中心作业单元树结构<br> 
   * <strong>Create on : 2016年9月10日 上午11:02:03<br></strong>
   * <p>
   * @param centerMap
   * @param centerUnitMap
   * @param workCenters
   * void
   * @throws 
   * @author dapeng.li<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  private void setChildren(Map<String, List<WorkCenter>> centerMap, Map<String, List<WorkUnit>> centerUnitMap,
      List<WorkCenter> workCenters) {
    for (WorkCenter workCenter : workCenters) {
      if (centerMap.containsKey(workCenter.getWorkCenterCode())) {
        workCenter.setChildrens(centerMap.get(workCenter.getWorkCenterCode()));
        setChildren(centerMap, centerUnitMap, workCenter.getChildrens());
      }
      if (centerUnitMap.containsKey(workCenter.getWorkCenterCode())) {
        workCenter.setWorkUnits(centerUnitMap.get(workCenter.getWorkCenterCode()));
      }
    }
  }

  @RequestMapping("getMsgConfigsByCondition")
  @ResponseBody
  public DWZResult getMsgConfigsByCondition(MessageConfigCondition condition) {
    if (StringUtils.isEmpty(condition.getWorkcenterCode()) && StringUtils.isEmpty(condition.getWorkunitCode())) {
      return ajaxDone(null);
    }
    if (StringUtils.isEmpty(condition.getSiteCode())) {
      condition.setSiteCode(getSiteCode());
    }
    return ajaxDone(messageConfigService.getMsgConfigsByCondition(condition));
  }

  @RequestMapping("addMsgConfig")
  public String addMsgConfig(Model model, String navTabId) {
    model.addAttribute(NAVTABID, navTabId);
    model.addAttribute(PATTERN, "add");
    return CONFIG_PAGE;
  }

  @RequestMapping("modifyMsgConfig")
  public String modifyMsgConfig(Model model, String navTabId, MessageConfig messageConfig) {
    model.addAttribute(NAVTABID, navTabId);
    model.addAttribute(PATTERN, "modify");
    model.addAttribute("msgConfig", messageConfigService.getMessageConfigById(messageConfig.getId(),
        StringUtils.isEmpty(messageConfig.getWorkcenterCode())));
    return CONFIG_PAGE;
  }

  @RequestMapping("viewMsgConfig")
  public String viewMsgConfig(Model model, String navTabId, MessageConfig messageConfig) {
    model.addAttribute(NAVTABID, navTabId);
    model.addAttribute(PATTERN, "view");
    model.addAttribute("msgConfig", messageConfigService.getMessageConfigById(messageConfig.getId(),
        StringUtils.isEmpty(messageConfig.getWorkcenterCode())));
    return CONFIG_PAGE;
  }

  @RequestMapping("copyMsgConfig")
  public String copyMsgConfig(Model model, String navTabId, MessageConfig messageConfig) {
    model.addAttribute(NAVTABID, navTabId);
    model.addAttribute("msgConfig", messageConfigService.getMessageConfigById(messageConfig.getId(),
        StringUtils.isEmpty(messageConfig.getWorkcenterCode())));
    return "mm/msgConfig/copyPage";
  }

  @RequestMapping("deleteMsgConfig")
  @ResponseBody
  public DWZResult deleteMsgConfig(String[] ids, String workcenterCode, String workunitCode,
      HttpServletRequest request) {
    if (ids.length == 0) {
      return ajaxError(getImeViewMessageI18n(null, SystemConstant.PARAMETERNULL));
    }
    BatchJobReport[] reports = new BatchJobReport[ids.length];
    int failures = 0;
    MessageConfig config;
    for (int i = 0; i < ids.length; i++) {
      config = new MessageConfig();
      config.setId(Long.valueOf(ids[i]));
      config.setWorkcenterCode(workunitCode);
      config.setWorkunitCode(workunitCode);
      reports[i] = messageConfigService.deleteMessageConfig(config);
      if (!reports[i].isSuccess()) {
        failures += 1;
      }
    }
    if (failures == 0) {
      return ajaxDone(null);
    } else {
      return batchjobAjaxDone(request, Arrays.asList(reports));
    }
  }
}
